import chalk from "chalk";
import { getNpmArgs } from "../utils/npmTag.js";

/**
 * 报告错误
 */
const reportError = () => {
  console.log(
    chalk.bgRed("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  );
  console.log(
    chalk.bgRed(
      `!! ${chalk.black.bold(
        "`npm publish` is forbidden for this package."
      )} !!`
    )
  );
  console.log(
    chalk.bgRed(
      `!! ${chalk.black.bold(
        "Use `npm run pub` instead.                  "
      )} !!`
    )
  );
  console.log(
    chalk.bgRed("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  );
};

/**
 * 发布前检查，必须使用脚手架发布，否则停止进程
 */
const prepublish = () => {
  const npmArgs = getNpmArgs();
  if (npmArgs) {
    for (let arg = npmArgs.shift(); arg; arg = npmArgs.shift()) {
      // 如果是publish 且不包含--with-package-cli-service，则不允许发布
      if (
        /^pu(b(l(i(sh?)?)?)?)?$/.test(arg) &&
        npmArgs.indexOf("--with-package-cli-service") < 0 &&
        !process.env.npm_config_with_package_cli_service
      ) {
        reportError();
        process.exit(1);
        return;
      }
    }
  }
};
export default prepublish;
